# Maintainer: gym603 <gui_yuan_miao@163.com>

_realname=re2
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
_pkgver=2020-08-01
pkgver=${_pkgver//-/}
pkgrel=1
pkgdesc="A fast, safe, thread-friendly alternative to backtracking regular expression engines like those used in PCRE, Perl, and Python (mingw-w64)"
arch=('any')
url="https://github.com/google/re2"
license=('custom')
depends=("${MINGW_PACKAGE_PREFIX}-gcc-libs")
makedepends=("${MINGW_PACKAGE_PREFIX}-cmake"
             "make"
             "${MINGW_PACKAGE_PREFIX}-gcc")
source=(${_realname}-${_pkgver}.tar.gz::https://github.com/google/re2/archive/${_pkgver}.tar.gz)
sha256sums=('6f4c8514249cd65b9e85d3e6f4c35595809a63ad71c5d93083e4d1dcdf9e0cd6')

# Helper macros to help make tasks easier #
apply_patch_with_msg() {
  for _patch in "$@"
  do
    msg2 "Applying ${_patch}"
    patch -Nbp1 -i "${srcdir}/${_patch}"
  done
}

prepare() {
  cd "${srcdir}/${_realname}-${_pkgver}"
}

build() {
  declare -a _extra_config
  if check_option "debug" "n"; then
    _extra_config+=("-DCMAKE_BUILD_TYPE=Release")
  else
    _extra_config+=("-DCMAKE_BUILD_TYPE=Debug")
  fi

  msg2 "Build static for ${MINGW_CHOST}"
  [[ -d "${srcdir}/build-${MINGW_CHOST}-static" ]] && rm -rf "${srcdir}/build-${MINGW_CHOST}-static"
  mkdir -p "${srcdir}/build-${MINGW_CHOST}-static" && cd "${srcdir}/build-${MINGW_CHOST}-static"

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
  ${MINGW_PREFIX}/bin/cmake \
    -G "MSYS Makefiles" \
    -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
    "${_extra_config[@]}" \
    -DRE2_BUILD_TESTING=ON \
    -DBUILD_SHARED_LIBS=OFF \
    ../${_realname}-${_pkgver}

${MINGW_PREFIX}/bin/cmake --build ./

  msg2 "Build shared for ${MINGW_CHOST}"
  [[ -d "${srcdir}/build-${MINGW_CHOST}-shared" ]] && rm -rf "${srcdir}/build-${MINGW_CHOST}-shared"
  mkdir -p "${srcdir}/build-${MINGW_CHOST}-shared" && cd "${srcdir}/build-${MINGW_CHOST}-shared"

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
  ${MINGW_PREFIX}/bin/cmake \
    -G "MSYS Makefiles" \
    -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
    "${_extra_config[@]}" \
    -DRE2_BUILD_TESTING=ON \
    -DBUILD_SHARED_LIBS=ON \
    ../${_realname}-${_pkgver}

${MINGW_PREFIX}/bin/cmake --build ./
}

check() {
  msg2 "Tests static for ${MINGW_CHOST}"
  cd "${srcdir}/build-${MINGW_CHOST}-static"
  ${MINGW_PREFIX}/bin/ctest ./ || true

  msg2 "Tests shared for ${MINGW_CHOST}"
  cd "${srcdir}/build-${MINGW_CHOST}-shared"
  ${MINGW_PREFIX}/bin/ctest ./ || true
}

package() {
  msg2 "Install static for ${MINGW_CHOST}"
  cd "${srcdir}/build-${MINGW_CHOST}-static"
  DESTDIR="${pkgdir}" ${MINGW_PREFIX}/bin/cmake --build ./ --target install

  msg2 "Install shared for ${MINGW_CHOST}"
  cd "${srcdir}/build-${MINGW_CHOST}-shared"
  DESTDIR="${pkgdir}" ${MINGW_PREFIX}/bin/cmake --build ./ --target install

  cd "${srcdir}/${_realname}-${_pkgver}"
  install -Dm644 LICENSE "${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}/LICENSE"
}
